package cn.powerchaintech.common.cimeparser;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CimEBlock {
    public static final String REGEX_BLOCK = "^<(([a-zA-Z0-9\\u4E00-\\u9FA5]+)::(\\S+))>$";
    private String clzName; // 类名
    private String insName; // 实例名
    private String blockFlag;
    private List<CimELine> lines = new ArrayList<>();
    private int rowCount = 0;

    public CimEBlock(String flag) {
        if (Pattern.matches(REGEX_BLOCK, flag)) {
            Matcher m = Pattern.compile(REGEX_BLOCK).matcher(flag);
            if (m.find()) {
                blockFlag = m.group(1);
                String[] ciPairs = blockFlag.split("::");
                clzName = ciPairs[0];
                insName = ciPairs[1];
            }
        }
    }

    public void append(String line) {
        if (!Pattern.matches(REGEX_BLOCK, line)) {
            CimELine cimELine = new CimELine(line);
            if (cimELine.getType().equals(CimELine.Type.DATA)) {
                rowCount++;
            }
            lines.add(cimELine);
        }
    }

    public static boolean IsStartBlock(String line) {
        return Pattern.matches(REGEX_BLOCK, line);
    }

    public boolean isEndBlock(String line) {
        return line.equals("</" + blockFlag + ">");
    }

    public String getClzName() {
        return clzName;
    }

    public String getInsName() {
        return insName;
    }

    public int rowCount() {
        return rowCount;
    }

    public int columnCount() {
        if (lines.isEmpty()) {
            return 0;
        }
        return lines.get(0).size();
    }

    public Iterator<Map<String, String>> iterator() {
        CimELine header = null;
        List<Map<String, String>> ls = new ArrayList<>();
        for (CimELine line : lines) {
            if (line.getType().equals(CimELine.Type.HEADER)) {
                header = line;
            }
            if (line.getType().equals(CimELine.Type.DATA)) {
                Map<String, String> m = new HashMap<>();
                for (int i = 0; i < Objects.requireNonNull(header).size(); i++) {
                    String h = header.get(i);
                    String d = line.get(i);
                    m.put(h, d);
                }
                ls.add(m);
            }
        }
        return ls.iterator();
    }
}
